#include "common.h"
void output_all(FILE * f);

extern void yyrestart ( FILE *input_file );
extern int yyparse();
extern void ir_optimize();
extern FILE * yyin;
FILE * YYERROR_OUTPUT;
FILE * temp_file(FILE * ir_in){
    size_t len = 0;
    static char buffer[BUFSIZ] = {};
    FILE *tmp = tmpfile();
    while ((len = fread(buffer, sizeof(char), BUFSIZ, ir_in)) > 0)
        fwrite(buffer, sizeof(char), len, tmp);  
    static char *append_code = "\n\n";
    fwrite(append_code, sizeof(char), strlen(append_code), tmp);
    fclose(ir_in);
    fseek(tmp, 0, SEEK_SET);
    return tmp;
}

int main(int argc,char ** argv){
    FILE * ir_in=stdin, * irout=stdout;
    if (argc > 1) {
        if (!(ir_in = fopen(argv[1], "r"))) {
            perror(argv[1]);
            return 1;
        }
        if (argc > 2&&!(irout = fopen(argv[2], "w"))) {
            perror(argv[2]);
            return 1;
        }
    }
    YYERROR_OUTPUT = stdout;
    yyin=temp_file(ir_in);
    yyparse();
    fclose(yyin);
    ir_optimize();
    output_all(irout);
    if(irout != stdout )fclose(irout);
}